package com.able.concurrency.t2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author abel.he
 * @data 2018/8/18 11:22
 * @describe ReentrantLock .lock() 到 .unlock() 里面的代码类似与synchronized方法快
 */
public class Test1 {

    private Lock lock = new ReentrantLock();

    void m1 () {
        try {
            lock.lock();  //锁定资源
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " 资源已经锁定: " + i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();   //释放锁
        }
    }

    public static void main(String[] args) {
        final Test1 test1 = new Test1();
        new Thread(new Runnable() {
            public void run() {
                test1.m1();
            }
        }, "Thread-0").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Runnable() {
            public void run() {
                test1.m1();
            }
        }, "Thread-1").start();
    }

}
